//
//  LogNewWeightViewController.m
//  iWeighMyself
//
//  Created by Francisco Gindre on 7/28/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LogNewWeightViewController.h"
#import "WeightScalePickerViewController.h"
#import "DatePickerViewController.h"
#import "DatabaseUtils.h"
@implementation LogNewWeightViewController
@synthesize currentEntry;
@synthesize appDelegate;
@synthesize sectionTitles;
//@synthesize weightCell;
#pragma mark -
#pragma mark constants

#define TOTAL_SECTIONS 2
#define WEIGHT_SECTION 0
#define DATE_SECTION 1


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	//Set the localized Title for the window
	self.title = NSLocalizedString(@"LogNewWeightViewTitle",@"");
	
	self.sectionTitles = [NSArray arrayWithObjects:NSLocalizedString(@"LogNewWeightViewWeight",@""),
						  NSLocalizedString(@"LogNewWeightViewDate",@""),nil];
	
	
	/*
	 get last entry, if nil, then do defaults
	 */
	self.appDelegate = [[UIApplication sharedApplication] delegate];
	
	Weight *lastWeightEntry = [DatabaseUtils queryNewestWeight:[appDelegate databasePath] fromTable:@"weight"];
	if (lastWeightEntry) {
		//self.currentEntry = [[Weight alloc]initWithWeightInKilos:lastWeightEntry.weightInKilos date:[NSDate date]];
		self.currentEntry = [[[Weight alloc ] initWithID:0 date:[NSDate date] 
										  weightInKilos:lastWeightEntry.weightInKilos 
										 weightInPounds:lastWeightEntry.weightInPounds 
												 isSent:0] retain];
	} else {
		//self.currentEntry = [[Weight alloc]initWithWeightInKilos:[NSNumber numberWithFloat:(float)60] date: [NSDate date]];
		self.currentEntry = [[[Weight alloc]initWithID:0 date:[NSDate date] weightInKilos:[NSNumber numberWithFloat:(float)60] 
														weightInPounds:[Weight 
														poundsFromKilos:[NSNumber numberWithFloat:(float)60]] 
											   isSent:0]retain ];
	}
	[currentEntry retain];
	NSLog(@"currentEntry: %@", self.currentEntry);

	[lastWeightEntry release];
    /*
	 set save button
	 */
	
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"SaveButtonTitle",@"")
																			  style:UIBarButtonItemStyleDone target:self action:@selector(saveWeight:)];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [self.sectionTitles objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    NSString *base;
	NSString *text;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	
	switch (indexPath.section) {
		case WEIGHT_SECTION:
			
			if ([self.appDelegate isKilosWeightSelectedUnit]) {
				
				base = [NSString stringWithFormat:@"%.1f ",[self.currentEntry.weightInKilos floatValue]];
				//NSLog(@"base string: %@",base);
				text = [base stringByAppendingString:NSLocalizedString(@"WeightUnitKilos",@"")];
				
				
				
			} else {
				base = [NSString stringWithFormat:@"%.1f ",[self.currentEntry.weightInPounds floatValue]];
				//NSLog(@"base string: %@",base);
				text = [base stringByAppendingString:NSLocalizedString(@"WeightUnitPounds",@"")];
				
			}
			
			
			
			break;
		case DATE_SECTION:
			
			text = [NSDateFormatter localizedStringFromDate:self.currentEntry.dateLogged
												  dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
			NSLog(@"text date:  %@",text);
			
			break;

	}
	[cell.textLabel setText:text];
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

	    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	WeightScalePickerViewController *weightPicker;
	switch (indexPath.section) {
		case WEIGHT_SECTION:
			/*
			 show the weight selector
			 */
			weightPicker = [[WeightScalePickerViewController alloc] initWithWeightAndParentView:currentEntry parentView:self];
			
			[self.navigationController pushViewController:weightPicker animated:YES];
			break;
	
		case DATE_SECTION:
			/*
			 
			 show Date picker
			 */
			
			[self.navigationController pushViewController:[[DatePickerViewController alloc]initWithParentView:self aDate:self.currentEntry.dateLogged] animated:YES];
			break;

	}
	[weightPicker release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark cell creation methods

/*
 returns a cell containing an UITextField configured as keyboard for text (not email)
 */

//- (UITableViewCell *) createEnterWeightAtIndexPath :(NSIndexPath*)indexPath tableView:(UITableView *) tableView  {
//	
//	static NSString *cellIdentifier = @"KeyBoardTextFieldCell";
//    
//    KeyBoardTextFieldCell *cell = (KeyBoardTextFieldCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//    
//	if (cell == nil) {
//		// get cell from the bundle
//		[[NSBundle mainBundle] loadNibNamed:@"KeyBoardTextFieldCellNib" owner:self options:nil];
//		
//		//pass the references to cell
//		cell = weightCell;
//		//self.nameCell = nil;
//	    
//    }
//	/*
//	 turn blue selection off
//	 */
//	
//	cell.selectionStyle = UITableViewCellSelectionStyleNone;
//	
//	/*
//	 set the delegate of the name text field
//	 */
//	
//	cell.nameTextField.delegate = self;
//	
//	//set the content of the UITextField inside the cell 
//	
//	NSString *base;
//	NSString *text;
//	if ([self.appDelegate isKilosWeightSelectedUnit]) {
//		
//		base = [NSString stringWithFormat:@"%.1f ",[self.currentEntry.weightInKilos floatValue]];
//		//NSLog(@"base string: %@",base);
//		text = [base stringByAppendingString:NSLocalizedString(@"WeightUnitKilos",@"")];
//		
//		
//		
//	} else {
//		base = [NSString stringWithFormat:@"%.1f ",[self.currentEntry.weightInPounds floatValue]];
//		//NSLog(@"base string: %@",base);
//		text = [base stringByAppendingString:NSLocalizedString(@"WeightUnitPounds",@"")];
//		
//	}
//	
//	[cell.nameTextField setText:text];
//	
//	/*
//	 release variables
//	 */
//	
//	[text release];
//	[base release];
//	
//	
//	return cell;
//	
//}

#pragma mark -
#pragma mark custom methods
/*
 loads last weight from database
 */

-(Weight*)loadLastWeight {
	return [DatabaseUtils queryNewestWeight:[appDelegate databasePath] fromTable:@"weight"];
}

/*
 saves the current weight and returns to main screen
 */
-(void)saveWeight:(id)sender {
	//NSLog(@"saving weight %@ date: %@",[self.currentEntry weightInKilos],[self.currentEntry dateLogged]);
	//NSLog(@"saveWeight:sender : %@", [self.currentEntry weightToString]);
	[DatabaseUtils insertWeightInDatabase:[appDelegate databasePath] weightToInsert:self.currentEntry intoTable:@"weight"];
	
	[self.navigationController popViewControllerAnimated:YES];
	
	
}

#pragma mark -
#pragma mark UITextFieldDelegate methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	
	if ([self.appDelegate isKilosWeightSelectedUnit]) {
		[self.currentEntry setWeightInKilos:[NSNumber numberWithFloat:[textField.text floatValue]]];
		
	} else {
		[self.currentEntry setWeightInPounds:[NSNumber numberWithFloat:[textField.text floatValue]]];
		
	}
	
	
}


@end

